<template>
  <div class="form">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="120px" label-position="right">
        <el-form-item label="Status" style="width: 260px;">
          <el-select v-model="searchForm.status" placeholder="" style="width: 140px;">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="find()" plain>Search</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column type="selection" width="50" align="center" />

        <el-table-column label="Pre-Stock in" align="center">
          <template v-slot="scope">
            <span>{{scope.row.source == "inventoryway" ?scope.row.quantity:0}}</span>
          </template>
        </el-table-column>
        <el-table-column label="Total Amount" align="center" width="150">
          <template v-slot="scope">
            <span>{{scope.row.quantity}}</span>
          </template>
        </el-table-column>
        <el-table-column label="Remain Amount" align="center" width="150">
          <template v-slot="scope">
            <span>{{scope.row.source == "inventory"?scope.row.quantity:0}}</span>
          </template>
        </el-table-column>
        <el-table-column label="Price" align="center" width="150">
          <template v-slot="scope">
            <span>{{scope.row.costprice}}</span>
          </template>
        </el-table-column>
        <el-table-column label="Expiration  Date" align="center">
          <template v-slot="scope">
            <span>{{scope.row.source == "inventory"?scope.row.batchnumberlist[0].expirationdate:""}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Certificates" width="140">
          <template slot-scope="scope">
            <div style="position: relative;">
              <a v-if="scope.row.batchnumber" style="font-size: 12px;" :href="scope.row.batchnumberlist[0].certificates"
                target="_blank"><img src="../../assets/pdf.png" style="width: 40px;height: 40px" />
              </a>
              <i v-else class="el-icon-upload"> Not Files </i>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="Supplier" align="center" width="180">
          <template v-slot="scope">
            <span>{{scope.row.suppliername}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Status" align="center">
          <template v-slot="scope">
            <span>Normal</span>
          </template>
        </el-table-column>

        <el-table-column label="createdTime" width="220">
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="Actions" width="200">
          <template slot-scope="scope">
            <el-button plain type="danger" v-permission="['attentions.destroy']"
              @click="uploadData(scope.row.batchnumberlist[0])">Update</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>
    <Uploadinv :show.sync="isShow" :module="module" :id="bid" :expiredate="expiredate" :contractfile="contractfile" />
  </div>
</template>
<script>
  import CURD from "@/mixin/CURD";
  import {
    index as skulist,
    update as skupdate
  } from "@/api/sku";
  import {
    productindex,
    index as prowarlist
  } from "@/api/inventory";
  import Uploadinv from "@/components/Uploadinv";
  export default {
    name: "skuIndex",
    components: {
      Uploadinv
    },
    props: {
      id: {
        type: String,
        default: 0
      }
    },
    mixins: [CURD],
    data() {
      return {
        status: [{
          id: null,
          name: "all",
        }, {
          id: "added",
          name: "added",
        }, {
          id: "notadded",
          name: "not added",
        }],
        tableData1: [],
        page: {
          total: null,
          per_page: 10,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        bid: "",
        expiredate: "",
        contractfile: "",
        cid: this.id,
        isEdit: false,
        isNew: false,
        formData: {},
        module: "sku",
        newTitle: "New sku",
        editTitle: "Edit sku",
        isPaginate: true,
        searchForm: {},
        imageUrl: "",
        dialogFormPasswordVisible: false,
        isUploadFile: false,
        importDialogVisible: false,
        fileReader: new FileReader(),
        isShow: false,
        rowIndex: 0,
      };
    },
    async created() {
      //this.searchForm.customer_id = this.cid;
      await this.fetchData();
    },
    methods: {
      changeAvatar(file, fileList) {
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
          console.log(reader.result)
        };
      },
      getUploadHandler(index) {
        return (options) => {
          this.rowIndex = index; // 如果需要在 uploadHandle 中使用，可以临时存储到组件的 data 或 properties 中
          this.uploadHandle(options);
        };
      },
      async uploadHandle(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.procureditem[this.rowIndex].certificates = data.url
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };
      },
      uploadData(row) {
        this.contractfile = row.contractfile
        this.expiredate = row.expiredate
        this.bid = row.id
        this.isShow = true;
      },
      saveData() {
        this.save("ruleForm");
      },
      handleUpdates(row, index) {
        const id = row.id
        var fd = {
          csku: row.inputvalue,
          id: row.id,
          action: "csku"
        }
        skupdate(fd).then(res => {
          this.$message.success(res.info)
          this.tableData[index].csku = row.inputvalue
        });
      },
      async fetchData() {
        this.searchForm.productid = this.cid;
        this.searchForm.type = 1;
        const res = await prowarlist(
          this.page.current_page,
          this.page.per_page,
          this.searchForm
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data
        } else {
          this.tableData = res.data
        }
        for (var i = 0; i < this.tableData.length; i++) {
          var ztquantity = 0;
          this.tableData[i]['ztquantity'] = ztquantity
        }

        let {
          rules
        } = require(`@/model/${this.module}`);
        this.rules = rules;
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      setTitle() {
        this.title = this.isNew === true ? this.newTitle : this.editTitle;
        this.cmdTitle = this.isNew === true ? "save" : "modify";
      },
      parseErrors(errors) {
        let info = "";
        let name = errors.name;
        if (Array.isArray(name)) {
          name.forEach((item) => {
            info += item + ",";
          });
        }
        info = info.substring(0, str.length - 1);
        return info;
      },
      async edit(id) {
        let {
          show
        } = require(`@/api/${this.module}`);
        let {
          data
        } = await show(id);
        this.formData = data;
        this.isNew = false;
        this.isEdit = true;
        this.setTitle();
        this.dialogFormVisible = true;
      },
      async del(id) {
        try {
          await this.$confirm("This operation will permanently delete data. Do you want to continue?", "prompt", {
            confirmButtonText: "determine",
            cancelButtonText: "cancel",
            type: "warning"
          });
          let {
            destroy
          } = require(`@/api/${this.module}`);
          let {
            info
          } = await destroy(id);
          this.$message.success(info);
          await this.fetchData();
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled deletion"
          });
        }
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>